<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// 使用相对路径导入API函数
import { getUserPage, updateUser } from '../../../api/user.js'

// 数据定义
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索条件
const searchUserId = ref('')
const searchUserName = ref('')

// 编辑模态框相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editForm = ref({})

// 初始化数据
onMounted(() => {
  fetchUserData()
})

// 获取用户分页数据
const fetchUserData = async () => {
  loading.value = true
  try {
    const res = await getUserPage(currentPage.value, pageSize.value, searchUserId.value, searchUserName.value)
    if (res.code === 200 && res.data) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error('获取用户数据失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取用户数据失败:', error)
    ElMessage.error('获取用户数据失败，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserData()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUserData()
}

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1
  fetchUserData()
}

// 重置搜索
const handleReset = () => {
  searchUserId.value = ''
  searchUserName.value = ''
  currentPage.value = 1
  fetchUserData()
}

// 打开编辑模态框
const openEditDialog = (row) => {
  // 深拷贝用户数据到编辑表单
  editForm.value = JSON.parse(JSON.stringify(row))
  editDialogVisible.value = true
}

// 处理更新用户
const handleUpdateUser = async () => {
  // 验证表单
  if (!editForm.value.userId || !editForm.value.userName) {
    ElMessage.warning('用户ID和用户名不能为空')
    return
  }

  editLoading.value = true
  try {
    // 构建更新数据，包含密码字段以避免密码被清空
    const updateData = {
      id: editForm.value.id,
      userId: editForm.value.userId,
      userName: editForm.value.userName,
      userType: editForm.value.userType,
      passWord: editForm.value.passWord // 保留原始密码，避免被更新为null
    }

    const res = await updateUser(updateData)
    if (res.code === 200) {
      ElMessage.success('更新用户成功')
      editDialogVisible.value = false
      // 刷新用户列表
      fetchUserData()
    } else {
      ElMessage.error(res.message || '更新用户失败')
    }
  } catch (error) {
    console.error('更新用户失败:', error)
    ElMessage.error(error.response?.data?.message || '更新用户失败，请稍后重试')
  } finally {
    editLoading.value = false
  }
}

// 获取用户类型文本
const getUserTypeText = (type) => {
  const typeMap = {
    0: '管理员',
    1: '教师',
    2: '学生'
  }
  return typeMap[type] || '未知'
}
</script>

<template>
  <div class="people-container">
    <h2 class="page-title">人员管理</h2>
    
    <el-card class="card-container" shadow="hover" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>人员列表</span>
          <div class="search-container">
            <el-input
              v-model="searchUserId"
              placeholder="搜索用户ID"
              style="width: 150px; margin-right: 10px;"
              type="number"
              clearable
              @keyup.enter="handleSearch"
            />
            <el-input
              v-model="searchUserName"
              placeholder="搜索用户名"
              style="width: 200px; margin-right: 10px;"
              clearable
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset" style="margin-left: 10px;">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="tableData" 
        style="width: 100%"
        border
      >
<!--        <el-table-column prop="id" label="记录ID" width="80" />-->
        <el-table-column prop="userId" label="学/工号" width="200" />
        <el-table-column prop="userName" label="用户名" width="200" />
        <el-table-column label="用户类型" width="200">
          <template #default="scope">
            {{ getUserTypeText(scope.row.userType) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" style="margin-top: 20px;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑用户模态框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="500px"
    >
      <el-form
        :model="editForm"
        label-width="100px"
        style="padding: 20px 0;"
      >
        <el-form-item
          label="用户ID"
          prop="userId"
        >
          <el-input
            v-model="editForm.userId"
            placeholder="请输入用户ID"
            type="number"

          />
        </el-form-item>
        <el-form-item
          label="用户名"
          prop="userName"
        >
          <el-input
            v-model="editForm.userName"
            placeholder="请输入用户名"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          label="用户类型"
          prop="userType"
        >
          <el-select
            v-model="editForm.userType"
            placeholder="请选择用户类型"
          >
            <el-option label="管理员" :value="0" />
            <el-option label="教师" :value="1" />
            <el-option label="学生" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateUser" :loading="editLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.people-container {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.card-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>